import { defineStore } from 'pinia'
import { login, logout, register, changePassword } from '@/services/auth'
import type { LoginParams, RegisterParams, ChangePasswordParams, User } from '@/services/auth'
import { ElMessage } from 'element-plus'
import router from '@/router'
import { jwtDecode } from 'jwt-decode'

interface State {
  token: string | null
  user: User | null
  loading: boolean
}

interface JwtPayload {
  user_id: number
  role: number
  exp: number
}

export const useAuthStore = defineStore('auth', {
  state: (): State => ({
    token: localStorage.getItem('token'),
    user: null,
    loading: false
  }),
  
  getters: {
    isAuthenticated: (state) => !!state.token,
    userRole: (state) => state.user?.role || 0
  },
  
  actions: {
    // 从token解析用户信息
    parseUserFromToken(token: string) {
      try {
        const decoded = jwtDecode<JwtPayload>(token)
        this.user = {
          id: decoded.user_id,
          role: decoded.role,
          username: '', // token中没有，先设为空
          created_at: '',
          updated_at: ''
        }
      } catch (error) {
        console.error('Token解析失败', error)
        this.user = null
      }
    },
    
    // 保存token
    setToken(token: string) {
      this.token = token
      localStorage.setItem('token', token)
      this.parseUserFromToken(token)
    },
    
    // 清除token
    clearToken() {
      this.token = null
      this.user = null
      localStorage.removeItem('token')
    },
    
    // 用户注册
    async register(userData: RegisterParams) {
      this.loading = true
      try {
        await register(userData)
        ElMessage.success('注册成功，请登录')
        router.push('/login')
        return true
      } catch (error) {
        return false
      } finally {
        this.loading = false
      }
    },
    
    // 用户登录
    async login(userData: LoginParams) {
      this.loading = true
      try {
        const res = await login(userData)
        if (res.token) {
          this.setToken(res.token)
          ElMessage.success('登录成功')
          router.push('/')
          return true
        }
        return false
      } catch (error) {
        return false
      } finally {
        this.loading = false
      }
    },
    
    // 用户登出
    async logout() {
      this.loading = true
      try {
        await logout()
        this.clearToken()
        ElMessage.success('已退出登录')
        router.push('/login')
      } catch (error) {
        // 即使API调用失败也要清除本地token
        this.clearToken()
        router.push('/login')
      } finally {
        this.loading = false
      }
    },
    
    // 修改密码
    async changePassword(passwordData: ChangePasswordParams) {
      this.loading = true
      try {
        await changePassword(passwordData)
        ElMessage.success('密码修改成功')
        return true
      } catch (error) {
        return false
      } finally {
        this.loading = false
      }
    },
    
    // 检查是否已登录，初始化时调用
    checkAuth() {
      if (this.token) {
        this.parseUserFromToken(this.token)
      }
    }
  }
}) 